import myServer from "@/server";
import { objectAssignDeep } from "albert.gao/common";
import {
  appStart,
  createBrowserWindow,
  handleIpcMainSync,
  installVueDevTools,
} from "albert.gao/default/electron-main";
import type { CreateExpressWsResult } from "albert.gao/node/network2";
// import { ExpressWssResult } from "albert.gao/node/network";
import { app } from "electron";

console.log({ versions: process.versions });

/**
 * 生成服务器并在'temp/server-settings.json'生成一个json文件
 */
async function createServer() {
  const server = myServer({
    production: app.isPackaged,
    changePortWhenOccupied: true,
    port: 80,
  });
  return server;
}

function createControlWindow(server: CreateExpressWsResult) {
  // let url = app.isPackaged
  //   ? Path.resolve(__dirname, "../../dist/vue/index.html")
  //   : "http://localhost:" + server.proxyPort;
  let url = "http://localhost:" + server.port;
  createBrowserWindow({
    url,
    mode: "loadURL",
    setConfig: (c) => {
      if (c.webPreferences) {
        objectAssignDeep(c, {
          width: 525,
          height: 520,
          resizable: false,
          frame: true,
          closable: false,
          maximizable: false,
          autoHideMenuBar: true,
          webPreferences: {
            contextIsolation: false,
          },
        });
      }
      return c;
    },
  });
}

(async () => {
  await appStart({
    onAllClosed: () => createControlWindow(server),
  });
  let server = await createServer();
  installVueDevTools();
  createControlWindow(server);

  // // baidu.com爬虫
  // createBrowserWindow({
  //   url: "http://baidu.com",
  //   setConfig: (c) => {
  //     // @ts-ignore
  //     c.webPreferences.preload = Path.resolve(
  //       __dirname,
  //       "../preloads/index.js"
  //     );
  //     return c;
  //   },
  // });

  handleIpcMainSync([
    {
      route: "kill-app",
      func: () => app.exit(),
    },
    {
      route: "server-settings",
      func: () => JSON.parse(JSON.stringify(server)),
    },
  ]);
})();
